//
//  StatusDAL.swift
//  JJWeibo
//
//  Created by JJ on 15/9/19.
//  Copyright © 2015年 JJ. All rights reserved.
//

import UIKit

private let clearCacheTimeTravel: NSTimeInterval = -60 * 60 * 24 * 5

class StatusDAL: NSObject {
    
    class func clearStatusCache() {
        
        let date = NSDate(timeIntervalSinceNow: clearCacheTimeTravel)
        let df = NSDateFormatter()
        df.dateFormat="yyyy-MM-dd HH:mm:ss"
        let str = df.stringFromDate(date)
        let sql = "DELETE FROM T_Status WHERE createTime < '\(str)'"
        if SQLiteManager.sharedManager.execSQL(sql){
            print("删除成功")
        }
    }
    
    class func loadStatus(since_id: Int, max_id: Int,complete:(array:[[String:AnyObject]]?)->()) {
        let list = loadCacheData(since_id, max_id: max_id)
        if list?.count ?? 0 > 0 {
            complete(array: nil)
            return
        }
        NetWorkTools.shareNetWorkTools.loadStatus(since_id: since_id, max_id: max_id).subscribeNext({ (result) -> Void in
           
            guard let array=result["statuses"] as? [[String:AnyObject]] else{
                complete(array: nil)
                return
            }
                saveStatus(array)
                complete(array: array)
            }, error: { (error) -> Void in
            
                complete(array: nil)
            }) { () -> Void in
                print("信号完成")
        }
        
    }
    
    
    class func loadCacheData(since_id: Int, max_id: Int)->[[String:AnyObject]]? {
        
        let userId=UserAccountViewModel.sharedUserAccount.userAccount!.uid!
        
        var sql="SELECT statusId, status, userId FROM T_Status \n" +
        "WHERE userId = \(userId) \n"
        
        if since_id>0{
            sql+="AND statusId > \(since_id) \n"
        }else if max_id>0{
            sql+="AND statusId < \(max_id) \n"
        }
        sql+="ORDER BY statusId DESC LIMIT 20;"
        
        var result:[[String:AnyObject]]?
        if let list = SQLiteManager.sharedManager.execRecordSet(sql){
            result=[[String:AnyObject]]()
            for item in list{
                
                let  statuString=item["status"] as! String
                let data = statuString.dataUsingEncoding(NSUTF8StringEncoding)!
                let dict=try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)) as! [String:AnyObject]
                result?.append(dict)
            }
           
        }
       return result
    }
    
    
    
    
    class func saveStatus(array:[[String:AnyObject]]) {
        
        let manager=SQLiteManager.sharedManager
        manager.beginTranscation()
        let sql="INSERT OR REPLACE INTO T_Status (statusId,status,userId) VALUES (?,?,?);"
        let userId=UserAccountViewModel.sharedUserAccount.userAccount!.uid!
        var result = true
        for dict in array{
            let statusId=dict["id"] as! Int
            let data=try! NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions(rawValue: 0))
            let jsonString=String(data: data, encoding: NSUTF8StringEncoding)!
            
           result = manager.prepareExecSQL(sql, parmas: userId,statusId,jsonString)
            if !result{
                break
            }
        }
        if result{
            print("提交事务")
            manager.commitTtansaction()
        }else{
            manager.rollBackTranscation()
        }
    }

}
